package com.blockmeta.bbs.immodule.greendao.repository;

import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.dao.CircleMember;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.greendao.db.CircleMemberDao;
import com.blockmeta.bbs.immodule.greendao.db.IMUserEntityDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * 包含了用户，圈子，圈子成员的数据操作和获取
 */
public class IMUserRepo implements IUserRepo {

    private IMUserEntityDao imUserEntityDao;
    private CircleMemberDao circleMemberDao;
    private SQLiteDatabase db;

    public IMUserRepo(IMUserEntityDao imUserEntityDao, CircleMemberDao circleMemberDao, SQLiteDatabase imdb) {
        this.imUserEntityDao = imUserEntityDao;
        this.circleMemberDao = circleMemberDao;
        this.db = imdb;
    }


    @Override
    public void updateUser(IMUserEntity user) {
        imUserEntityDao.update(user);
    }


    @Override
    public IMUserEntity getUser(long whoId, long userId, int type) {
        QueryBuilder<IMUserEntity> qb = imUserEntityDao.queryBuilder();
        return qb.where(IMUserEntityDao.Properties.WhoId.eq(whoId), IMUserEntityDao.Properties.Type.eq(type), IMUserEntityDao.Properties.UserId.eq(userId)).unique();
    }

    /**
     * 获取通讯录好友列表
     *
     * @param whoId
     * @return
     */
    @Override
    public List<IMUserEntity> getBookListFriends(long whoId) {
        List<IMUserEntity> list = imUserEntityDao.queryBuilder().where(IMUserEntityDao.Properties.WhoId.eq(whoId)
                , IMUserEntityDao.Properties.Type.eq(Params.USER_PERSON), IMUserEntityDao.Properties.IsFriend.eq(true)).list();
        return list;
    }


    /**
     * 获取通讯录群列表！
     *
     * @param whoId
     * @return
     */
    @Override
    public List<IMUserEntity> getGroupListFriends(long whoId) {
        List<IMUserEntity> list = imUserEntityDao.queryBuilder().where(IMUserEntityDao.Properties.WhoId.eq(whoId)
                , IMUserEntityDao.Properties.Type.eq(Params.USER_GROUP)).list();
        return list;
    }



    @Override
    public List<Long> getNoDisturbGroupIds(long uidInt) {
        QueryBuilder<IMUserEntity> qb = imUserEntityDao.queryBuilder();
        List<IMUserEntity> list = qb.where(IMUserEntityDao.Properties.WhoId.eq(uidInt), IMUserEntityDao.Properties.Type.eq(Params.USER_GROUP)
                , IMUserEntityDao.Properties.NoDisturb.eq(true)).list();
        List<Long> ids = new ArrayList<>();
        for (IMUserEntity entity : list) {
            ids.add(entity.getUserId());
        }
        return ids;
    }

    @Override
    public List<IMUserEntity> getGroupListMyGroupFirst(long whoId) {
        List<IMUserEntity> list = imUserEntityDao.queryBuilder().where(IMUserEntityDao.Properties.WhoId.eq(whoId)
                , IMUserEntityDao.Properties.Type.eq(Params.USER_GROUP)
                , IMUserEntityDao.Properties.CreateUserId.eq(whoId)).list();
        List<IMUserEntity> listNotMy = imUserEntityDao.queryBuilder().where(IMUserEntityDao.Properties.WhoId.eq(whoId)
                , IMUserEntityDao.Properties.Type.eq(Params.USER_GROUP)
                , IMUserEntityDao.Properties.CreateUserId.notEq(whoId)).list();
        list.addAll(listNotMy);
        return list;
    }

    @Override
    public List<CircleMember> getCircleMembers(long chatGroupId, long whoId) {
        return circleMemberDao.queryBuilder().where(CircleMemberDao.Properties.WhoId.eq(whoId),
                CircleMemberDao.Properties.GroupId.eq(chatGroupId)).list();
    }

    @Override
    public void deleteCircleMember(Long circleMemberId) {
        circleMemberDao.deleteByKey(circleMemberId);
    }

    @Override
    public void addCircleMember(long uidInt, CircleMember circleMember) {
        circleMember.setWhoId(uidInt);
        circleMemberDao.insertOrReplace(circleMember);
    }

    @Override
    public CircleMember getCircleMember(long uidInt, long userId, long chatGroupId) {
        QueryBuilder<CircleMember> qb = circleMemberDao.queryBuilder();
        try {
            CircleMember unique = qb.where(CircleMemberDao.Properties.WhoId.eq(uidInt)
                    , CircleMemberDao.Properties.UserId.eq(userId)
                    , CircleMemberDao.Properties.GroupId.eq(chatGroupId)).unique();
            return unique;
        }catch (Exception e){
        }
        return null;
    }

    @Override
    public List<IMUserEntity> searchIMUserPaged(String word, int pageSize, int page, String orderField, String orderType, int type) {
        QueryBuilder<IMUserEntity> qb = imUserEntityDao.queryBuilder();
        if(type == Params.USER_PERSON){
            qb.where(IMUserEntityDao.Properties.WhoId.eq(AccountHelper.getUidInt())
                    ,IMUserEntityDao.Properties.Type.eq(type)
                    ,IMUserEntityDao.Properties.IsFriend.eq(true)
                    ,qb.or(IMUserEntityDao.Properties.Name.like("%" + word + "%")
                            , IMUserEntityDao.Properties.RemarkName.like("%" + word + "%")));
        }else {
            qb.where(IMUserEntityDao.Properties.WhoId.eq(AccountHelper.getUidInt())
                    ,IMUserEntityDao.Properties.Type.eq(type)
                    ,IMUserEntityDao.Properties.Name.like("%" + word + "%"));

        }
        if(TextUtils.isEmpty(orderField)){
            qb.orderAsc(IMUserEntityDao.Properties.Id);
            qb.offset(page * pageSize).limit(pageSize);
        }
        return qb.list();
    }

    @Override
    public void updateCircleMember(CircleMember circleMember) {
        circleMemberDao.update(circleMember);
    }

    @Override
    public void addUser(IMUserEntity imUserEntity) {
        imUserEntityDao.insertOrReplace(imUserEntity);
    }

    @Override
    public void delete(IMUserEntity entity) {
        imUserEntityDao.delete(entity);
    }

    /**
     * 会更新是否好友状态的
     * @param uidInt
     * @param user
     * @return
     */
    @Override
    public IMUserEntity addAndUpdateUser(long uidInt, IMUserEntity user) {
        try {
            IMUserEntity unique = getUser(uidInt, user.getUserId(), user.getType());
            if (unique != null) {
                unique.setRemarkName(user.getRemarkName());
                unique.setAvatarPath(user.getAvatarPath());
                unique.setFriend(user.isFriend());
                unique.setName(user.getName());
                unique.setIdentification(user.getIdentification());
                updateUser(unique);
                return unique;
            } else {
                addUser(user);
                return user;
            }
        } catch (Exception e) {
            //其实不用捕获，解决多进程线程下同步插入不会抛出异常，直接不会执行最终插入的
            LogUtils.d("user or circle insert duplicate");
        }
        return null;
    }

    /**
     * 不会更新好友状态只更新基本信息
     * @param uidInt
     * @param user
     * @return
     */
    @Override
    public IMUserEntity addAndUpdateUserInfo(int uidInt, IMUserEntity user) {
        try {
            IMUserEntity unique = getUser(uidInt, user.getUserId(), user.getType());
            if (unique != null) {
                unique.setRemarkName(user.getRemarkName());
                unique.setAvatarPath(user.getAvatarPath());
                unique.setName(user.getName());
                unique.setIdentification(user.getIdentification());
                unique.setSignature(user.getSignature());
                updateUser(unique);
                return unique;
            } else {
                addUser(user);
                return user;
            }
        } catch (Exception e) {
            //其实不用捕获，解决多进程线程下同步插入不会抛出异常，直接不会执行最终插入的
            LogUtils.d("user or circle insert duplicate");
        }
        return null;
    }

}
